package org.base.admin.config.security;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

import org.base.dao.modules.sys.model.SysUserDO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

public final class JwtUserFactory {

    private JwtUserFactory() {
    }

    public static JwtUser create(SysUserDO user) {
        return new JwtUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                mapToGrantedAuthorities(user.getAuthorities()),
                user.getEnabled(),
                user.getLastPasswordResetDate(),
                user.isAdmin()
        );
    }
    
    public static SysUserDO createSysUser(JwtUser user) {
    	SysUserDO sysUser = new SysUserDO();
    	sysUser.setId(user.getId());
    	sysUser.setUsername(user.getUsername());
    	sysUser.setEnabled(user.isEnabled());
    	sysUser.setLastPasswordResetDate(user.getLastPasswordResetDate());
    	sysUser.setAdmin(user.isAdmin());
    	return sysUser;
    }

    private static Set<GrantedAuthority> mapToGrantedAuthorities(Set<String> authorities) {
    	if (authorities == null) return new HashSet<>();
        return authorities.stream()
                .map(authority -> new SimpleGrantedAuthority(authority))
                .collect(Collectors.toSet());
    }
}
